import { useAPIUtils } from "@/components/APIUtilsProvider";
import { WithwingsDropzone } from "@/components/WithwingsDropzone";
import { Box, Button, Grid, Group, PasswordInput, Text } from "@mantine/core";
import { useForm } from "@mantine/form";
import { notifications } from "@mantine/notifications";
import PageLayout from "../components/PageLayout";

function Settings() {
  return (
    <>
      <PageLayout title={"个人设置"}>
        <Grid w="96%">
          <Grid.Col span={6}>
            <Text size={"md"} mb={24}>
              更改密码
            </Text>
            <ChangePasswordSection />
          </Grid.Col>
          <Grid.Col span={4}>
            <Text size={"md"} mb={24}>
              更换头像
            </Text>
            <ChangeAvatarSection />
          </Grid.Col>
        </Grid>
      </PageLayout>
    </>
  );
}

function ChangeAvatarSection() {
  const { restPUT, tanstackQuery, tanstackInvalidate } = useAPIUtils();

  const query = tanstackQuery(`/api/me`);

  const changeAvatar = async (url) => {
    await restPUT(`/api/avatar/mine`, { avatar: url });
    tanstackInvalidate("/api/me");
  };

  if (!query.data) {
    return;
  }

  return (
    <>
      <WithwingsDropzone
        src={query.data.user.meta.avatar}
        onSuccess={changeAvatar}
      />
    </>
  );
}

function ChangePasswordSection() {
  const form = useForm({
    initialValues: {
      oldPassword: "",
      newPasswordConfirm: "",
      newPassword: "",
    },

    validate: {},
  });

  const { restPUT } = useAPIUtils();

  const changePassword = async ({
    oldPassword,
    newPassword,
    newPasswordConfirm,
  }) => {
    if (newPassword !== newPasswordConfirm) {
      notifications.show({
        title: "两次输入的不匹配",
        color: "red",
      });
      return;
    }
    await restPUT(`/api/password/mine`, { oldPassword, newPassword });
    form.reset();
  };

  return (
    <Box maw={340}>
      <form onSubmit={form.onSubmit(changePassword)}>
        <PasswordInput label="原密码" {...form.getInputProps("oldPassword")} />
        <PasswordInput
          label="新密码"
          placeholder="8位以上数字和字母的组合"
          {...form.getInputProps("newPassword")}
        />
        <PasswordInput
          label="重复确认"
          {...form.getInputProps("newPasswordConfirm")}
        />

        <Group justify="flex-end" mt="md">
          <Button type="submit">更新密码</Button>
        </Group>
      </form>
    </Box>
  );
}

export default Settings;
